const router = require('koa-router')()
const { exec } = require('../sql')
const { SuccessModel, FailModel } = require('../resModel')
// 接口和数据库结合使用
// async  / await 结合promise处理异步
// 让代码变成同步输出
// restful api
/**
 * @name Restful-Api
 * @概念 不同的请求方式，同一个url
 * get
 * post
 * put
 * delete
 * url: http://localhost:8000/api/blogs
 */

// 查
router.get('/api/blogs', async (ctx, next) => {
  const { page = 1, size = 5 } = ctx.query
  try {
    const sql = `select * from blogs limit ? offset ?`
    const data = await exec(sql, [size * 1, (page - 1) * size])
    ctx.body = new SuccessModel('success', data)
  } catch (err) {
    ctx.body = new FailModel('fail', err)
  }
})
// 增
router.post('/api/blogs', async (ctx, next) => {
  const { title, content, author } = ctx.request.body
  try {
    const sql = `insert into blogs (title, content, author) values (?, ?, ?)`
    const data = await exec(sql, [title, content, author])
    if (data.affectedRows) {
      ctx.body = new SuccessModel('success', data)
    } else {
      ctx.body = new FailModel('fail')
    }
  } catch (err) {
    ctx.body = new FailModel('fail', err)
  }
})

// 改
router.put('/api/blogs', async (ctx, next) => {
  const { title, content, author, id } = ctx.request.body
  console.log('ctx.request.body:', ctx.request.body)
  try {
    const sql = `update blogs set title=?, content=?, author=? where id = ?`
    const data = await exec(sql, [title, content, author, id])
    if (data.affectedRows) {
      ctx.body = new SuccessModel('success', data)
    } else {
      ctx.body = new FailModel('修改失败')
    }
  } catch (err) {
    ctx.body = new FailModel('fail', err)
  }
})
// 删
router.delete('/api/blogs', async (ctx, next) => {
  const { id } = ctx.query
  try {
    const sql = `delete from blogs where id=?`
    const data = await exec(sql, [id])
    if (data.affectedRows) {
      ctx.body = new SuccessModel('success', data)
    } else {
      ctx.body = new FailModel('fail')
    }
  } catch (err) {
    ctx.body = new FailModel('fail', err)
  }
})

// router.delete('/api/blogs/:id', async (ctx, next) => {
//   const { id } = ctx.params
//   console.log('id:', ctx.params)
//   ctx.body = ctx.params
//   // try {
//   //   const sql = `delete from blogs where id=?`
//   //   const data = await exec(sql, [id])
//   //   ctx.body = data
//   // } catch (err) {
//   //   ctx.body = err
//   // }
// })

module.exports = router
